/**
 * 
 */
package com.gmail.hh.flickrj.sample.android.tasks;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import android.os.AsyncTask;

import com.gmail.hh.flickrj.sample.android.FlickrHelper;
import com.googlecode.flickrjandroid.Flickr;
import com.googlecode.flickrjandroid.contacts.Contact;
import com.googlecode.flickrjandroid.oauth.OAuth;
import com.googlecode.flickrjandroid.oauth.OAuthToken;
import com.googlecode.flickrjandroid.people.User;

public class LoadContactsTask extends AsyncTask<OAuth, Void, Collection<User> > {

	/**
	 *  Load Contacts asynchron, invoke callback handler after loading
	 *  author: helmut
	 */

	// each Class using this Loader  must implement this interface
	IContactsLoadedListener mCallbackContactsLoaded;
	public interface IContactsLoadedListener {
		public void onContactsLoaded(Collection<User> contacts);
	}
	

	/**
	 * @param flickrjAndroidSampleActivity
	 */
	public LoadContactsTask(IContactsLoadedListener callbackContactsLoaded) {
		this.mCallbackContactsLoaded = callbackContactsLoaded;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Collection<User> doInBackground(OAuth... arg0) {
		OAuthToken token = arg0[0].getToken();
		Flickr f = FlickrHelper.getInstance().getFlickrAuthed(token.getOauthToken(), 
				token.getOauthTokenSecret());
		try {
			Collection<Contact> contacts = f.getContactsInterface().getList();
			// Return User-Objects 
			ArrayList<User> contactsUser = new ArrayList<User>();
			for (Contact contact: contacts) {
				User user = f.getPeopleInterface().getInfo(contact.getId() );
				if (user!=null) {
					contactsUser.add(user);
				}
			}
			return contactsUser;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(Collection<User> contacts) {
		if (this.mCallbackContactsLoaded != null ) {
			this.mCallbackContactsLoaded.onContactsLoaded(contacts);
		}
	}
	
}